package com.mofang.powerdekorhelper.activity.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.mofang.powerdekorhelper.R;
import com.mofang.powerdekorhelper.adapter.PastActivityListAdapter;
import com.mofang.powerdekorhelper.adapter.SignInListAdapter;
import com.mofang.powerdekorhelper.base.MvpActivity;
import com.mofang.powerdekorhelper.base.recycleview.BaseRecycleViewAdapter;
import com.mofang.powerdekorhelper.base.recycleview.BaseRecycleViewList;
import com.mofang.powerdekorhelper.model.ActivityDetail;
import com.mofang.powerdekorhelper.model.ActivityList;
import com.mofang.powerdekorhelper.model.PastActivityList;
import com.mofang.powerdekorhelper.persenter.ActivityDetailPersenter;
import com.mofang.powerdekorhelper.utils.Constants;
import com.mofang.powerdekorhelper.utils.DialogUtils;
import com.mofang.powerdekorhelper.utils.GlideLoader;
import com.mofang.powerdekorhelper.utils.LoadPrograss;
import com.mofang.powerdekorhelper.utils.NetUtiles;
import com.mofang.powerdekorhelper.utils.SharePerforenceUtils;
import com.mofang.powerdekorhelper.utils.ShareUtils;
import com.mofang.powerdekorhelper.utils.T;
import com.mofang.powerdekorhelper.view.ActivityDetailView;
import com.mofang.powerdekorhelper.witget.MyWebViewClient;
import com.mofang.powerdekorhelper.witget.TitleBar;

import java.io.File;
import java.util.List;

import butterknife.BindView;

/**
 * Created by luofei on 2017/8/24 0024.
 * <p>
 * 活动详情
 */

public class ActivityDetailAct extends MvpActivity<ActivityDetailView, ActivityDetailPersenter> implements ActivityDetailView {

    @BindView(R.id.activity_detail_title)
    TitleBar mTitleBar;

    @BindView(R.id.activity_detial_head_imv)
    ImageView headImv;

    @BindView(R.id.activity_detial_name_tv)
    TextView nameTv;

    @BindView(R.id.activity_detial_seen_num)
    TextView seenNumTv;

    @BindView(R.id.sign_up_num)
    TextView signUpTv;

    @BindView(R.id.activity_time_tv)
    TextView timeTv;

    @BindView(R.id.activity_address_tv)
    TextView addressTv;

    @BindView(R.id.activity_detial_scrollview)
    ScrollView scrollView;

    @BindView(R.id.activity_sign_list)
    BaseRecycleViewList signList;

    @BindView(R.id.activity_detail_past_list)
    BaseRecycleViewList pastList;

    @BindView(R.id.activity_detail_web)
    WebView mWebView;

    @BindView(R.id.activity_detail_rule)
    TextView detailRuleTv;

    private int activityId;
    private int customerId;

    ActivityList activityList;

    LoadPrograss loadPrograss;

    private static final int THUMB_SIZE = 150;

    private String qrCodeUrl;

    private int page = 1;
    private int pageSize = 10;
    private Integer shopId;

    private File localQrcodeImage;
    private String activityTitle;

    private List<Bitmap> qrCodeBitmaps;

    @Override
    public void initView() {

        inflateLayout(R.layout.activity_detail_layout);
        initTitleBar();
        loadPrograss = new LoadPrograss(this);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        linearLayoutManager.canScrollVertically();
        pastList.setLayoutManager(linearLayoutManager);

        WebSettings webSettings = mWebView.getSettings();//获取webview设置属性
        webSettings.setJavaScriptEnabled(true);//支持js
        mWebView.setWebViewClient(new MyWebViewClient());

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        linearLayoutManager1.canScrollVertically();
        signList.setLayoutManager(linearLayoutManager1);
    }

    @Override
    public void initData() {
        shopId = SharePerforenceUtils.getInstance(this).getShopId();
        activityId = getIntent().getIntExtra("ActivityId", -1);
        activityList = (ActivityList) getIntent().getSerializableExtra("ActivityList");
        activityId = getIntent().getIntExtra("ActivityId", activityId);
        presenter.getActivityDetail(activityId);
        presenter.getPastActivityList(page, pageSize, shopId);
    }

    @Override
    public void setActivityDetail(ActivityDetail activityDetail) {

        final ActivityDetail.Result result = activityDetail.getResult();

        GlideLoader.getInstance(this).loadImage(result.getImgurl(), headImv);

        activityTitle = result.getName();

        nameTv.setText(activityTitle);

        int num = 0;
        if (result.getPictures() != null) {
            num = result.getPictures().size();
        }
        signUpTv.setText(num + "\n人报名");

        timeTv.setText(result.getStart_time() + "---" + result.getEnd_time());

        addressTv.setText(result.getStage());

        seenNumTv.setText(result.getLook() + "");

        mWebView.loadDataWithBaseURL(null, activityDetail.getResult().getDetails(), "text/html", "utf-8", null);

        SignInListAdapter adapter1 = new SignInListAdapter(result.getPictures(), this, R.layout.sign_up_list_item_layout);
        adapter1.setOnItemClickListner(new BaseRecycleViewAdapter.OnItemClickListner() {
            @Override
            public void onItemClickListner(ViewGroup parent, View v, int position) {

                startActivity(new Intent(ActivityDetailAct.this, ActivitySignInAct.class)
                        .putExtra("ActivityId", activityId)
                        .putExtra("SignInList", result));
            }
        });
        signList.setAdapter(adapter1);

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < activityDetail.getResult().getItmes().size(); i++) {

            sb.append(activityDetail.getResult().getItmes().get(i).getView_msg() + "\n");
        }

        detailRuleTv.setText(sb.toString());

        scrollView.scrollTo(0, 0);

        hideProgress();
    }

    @Override
    public void setPastActivityList(PastActivityList pastActivityList) {
        // 往期活动
        PastActivityListAdapter activityListAdapter = new PastActivityListAdapter(pastActivityList.getData(), this, R.layout.past_activity_list_item_layout);

        activityListAdapter.setOnItemClickListner(new BaseRecycleViewAdapter.OnItemClickListner() {
            @Override
            public void onItemClickListner(ViewGroup parent, View v, int position) {

                PastActivityList.Data data = (PastActivityList.Data) v.getTag();

                presenter.getActivityDetail(data.getAid());
            }
        });

        pastList.setAdapter(activityListAdapter);
    }

    Dialog shareInfoDialog = null;
    private Dialog sharedDialog;
    private String mShareInfo = "";

    public void initTitleBar() {
        initTitleBarWithback(mTitleBar, R.string.activity_detial_title);
        mTitleBar.addAction(new TitleBar.TextAction("分享") {
            @Override
            public void performAction(View view) {

                sharedDialog = DialogUtils.getInstance().MySharedDialog(ActivityDetailAct.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        switch (v.getId()) {

                            case R.id.share_wechat_imv:

                                //shareUtils.shareMinProgram(activityTitle, shareInfo, Constants.ACTIVITY_SHARE_CODE, activityId);
                                showShareInfoDialog();

                                break;
                            case R.id.share_moments_imv:

                                presenter.getQrCode(3, activityId, false);
                                //shareUtils.shareMinProgram(activityTitle, shareInfo, Constants.ACTIVITY_SHARE_CODE, activityId);
                                break;

                            case R.id.share_cancle_tv:
                                sharedDialog.dismiss();
                                break;
                        }
                        sharedDialog.dismiss();
                    }
                });
                sharedDialog.show();
            }
        });
    }

    private void showShareInfoDialog() {

        final ShareUtils shareUtils = new ShareUtils(ActivityDetailAct.this);

        shareInfoDialog = DialogUtils.getInstance().shareInfoDialog(ActivityDetailAct.this, new DialogUtils.IShareInfo() {
            @Override
            public void getShareInfo(String shareInfo) {
                if (!shareInfo.equals("")) {
                    mShareInfo = shareInfo;

                    shareInfoDialog.dismiss();

                    String node3Img = SharePerforenceUtils.getInstance(ActivityDetailAct.this).getNode3Image();

                    new AsyncTask<String, Void, Bitmap>() {

                        @Override
                        protected Bitmap doInBackground(String... params) {
                            return new NetUtiles().getBitmap(params[0]);
                        }

                        @Override
                        protected void onPostExecute(Bitmap bitmap) {
                            super.onPostExecute(bitmap);
                            if (bitmap != null) {
                                shareUtils.shareMinProgram(activityTitle, mShareInfo, Constants.ACTIVITY_SHARE_CODE, activityId, bitmap);
                            } else {
                                toast("抱歉，获取分享数据失败");
                            }
                        }
                    }.execute(node3Img);

                } else {
                    toast("请输入分享内容");
                    //showShareDialog(mShareInfo);
                    shareInfoDialog.dismiss();
                }
            }

            @Override
            public void cancleDialog() {
                shareInfoDialog.dismiss();
            }
        });

        shareInfoDialog.show();
    }

    @Override
    public void setQrCode(String qrCode) {

        if (qrCode != null && !qrCode.equals("")) {
            this.qrCodeUrl = qrCode;
        }

        showProgress();

        String nodeId = SharePerforenceUtils.getInstance(this).getNodeId();
        String shareBgUrl = Constants.shareBgImageUrl1 + nodeId + "001.jpg";
        new NetUtiles().getImageBitmap(this, shareBgUrl, qrCodeUrl, new NetUtiles.ICorvertImage2() {
            @Override
            public void corvertSuccess(List<Bitmap> bitmap) {

                qrCodeBitmaps = bitmap;

                localQrcodeImage = new NetUtiles().mergeBitmap(qrCodeBitmaps.get(0), qrCodeBitmaps.get(1));
                new ShareUtils(ActivityDetailAct.this).shareToTimeLine(ActivityDetailAct.this, localQrcodeImage);
                //new ShareUtils(ActivityDetailAct.this).shareLocalImage(ActivityDetailAct.this, SHARE_MEDIA.WEIXIN_CIRCLE, localQrcodeImage, "");

                hideProgress();
            }

            @Override
            public void covertFail() {
                toast("二维码获取失败,请重试");
            }
        });

        hideProgress();

        //shareInfoDialog.dismiss();

    }

    @Override
    public void showProgress() {
        loadPrograss.show();
    }

    @Override
    public void hideProgress() {
        loadPrograss.hide();
    }

    @Override
    public void toast(CharSequence s) {
        T.showShort(this, s);
    }

    @Override
    public void toast(int id) {

    }

    @Override
    public void showNullLayout() {

    }

    @Override
    public void hideNullLayout() {

    }

    @Override
    public void showErrorLayout(View.OnClickListener listener) {

    }

    @Override
    public void hideErrorLayout() {

    }

    @Override
    public void onError(String errorInfo) {
        toast(errorInfo);
        loadPrograss.hide();
    }

    @Override
    public ActivityDetailPersenter initPresenter() {
        return new ActivityDetailPersenter();
    }
}
